package com.qf.wangqing.sportsnews.utils;

import android.databinding.BindingAdapter;
import android.databinding.InverseBindingListener;
import android.databinding.InverseBindingMethod;
import android.databinding.InverseBindingMethods;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.qf.wangqing.sportsnews.bean.newstitletype2.TitleCommentComments;
import com.qf.wangqing.sportsnews.bean.newstitletype2.TitleViewData;
import com.squareup.picasso.Picasso;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by wuyang on 2016/12/16.
 */
@InverseBindingMethods({
        @InverseBindingMethod(type = ViewPager.class,attribute = "currentItem",method = "getCurrentItem")
})
public class NewsBindings {
    @BindingAdapter("loadUrl")
    public static void getImage(ImageView view,String url){
        Log.i("url","123"+url);
        Picasso.with(view.getContext())
                .load(url)
                .into(view);
    }
    @BindingAdapter("loadUrls")
    public static void getImages(ImageView view,String url){
        String images = "http://lifeixphoto.qiniudn.com/"+url;
        Picasso.with(view.getContext())
                .load(images)
                .into(view);
    }



    @BindingAdapter({"childCount","childLayout"})
    public static void loadRadioButton(RadioGroup group,int count,int childLayoutId){
            group.removeAllViews();
        LayoutInflater inflater = LayoutInflater.from(group.getContext());

        for (int i = 0; i < count; i++) {
            View view = inflater.inflate(childLayoutId, group, false);
            view.setId(i);
            group.addView(view);
        }
    }
    @BindingAdapter("currentItem")
    public static void setCurrentItem(ViewPager pager,int item){
        pager.setCurrentItem(item);
    }
    @BindingAdapter("currentItemAttrChanged")
    public static void setCurrentItemChanged(ViewPager pager, final InverseBindingListener listener){
        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                listener.onChange();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }
    //ViewPager自动播放的属性
    @BindingAdapter("autoPlayDelayed")
    public static void setAutoPlayDelayed(final ViewPager pager, final int delayed){
      Handler handler = (Handler) pager.getTag();
        if (handler == null) {
            handler = new Handler(Looper.getMainLooper()){
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what){
                        case 0:
                            int index = pager.getCurrentItem()+1;
                            if (index>=pager.getAdapter().getCount()){
                                 index = 0;
                            }
                            pager.setCurrentItem(index,false);
                            sendEmptyMessageDelayed(0,delayed);
                            break;
                    }
                }
            };
            pager.setTag(handler);
        }
        handler.removeMessages(0);
        if (delayed>0) {
            handler.sendEmptyMessageDelayed(0,delayed);
        }
    }

    //加载webview的方法
    @BindingAdapter("loadWebview")
    public static void loadWebView(WebView view,Object d){
        String content = ((TitleViewData)d).getText_content();
        List<String> images = ((TitleViewData)d).getText_images();
        Matcher matcher = Pattern.compile("\\$\\{lx-(\\w+)-?(\\d*)\\}").matcher(content);
        StringBuffer buffer = new StringBuffer("<style>img{max-width:100%}</style>");
        while (matcher.find()) {
            switch (matcher.group(1)) {
                case "br":
                    matcher.appendReplacement(buffer, "<br/>");
                    break;
                case "image":
                    matcher.appendReplacement(buffer, String.format(Locale.getDefault(), "<img src=\"%s\"/>", images.get(Integer.parseInt(matcher.group(2)))));
                    break;
            }
        }
        matcher.appendTail(buffer);
        view.loadData(buffer.toString(), "text/html; charset=utf-8;", "UTF-8");
    }
    private static final SimpleDateFormat TO_TIME = new SimpleDateFormat("HH:mm", Locale.getDefault());
    //获取评论时间
    @BindingAdapter("time")
    public static void getCommentTime(TextView view,Object d){
        Date currentTime = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = format.format(currentTime);
        String currentT = dateString.substring(12,16);
//        String commentTime = TO_TIME.format(((TitleCommentComments)d).getCreate_time());
        String commentTime = ((TitleCommentComments)d).getCreate_time().substring(12,16);
        String[] kk = currentT.split(":");
        String[] jj = commentTime.split(":");
        double s = Double.parseDouble(kk[0])+Double.parseDouble(kk[1])/60;
        double c = Double.parseDouble(jj[0])+Double.parseDouble(jj[1])/60;
        String result = "";
        if (s-c<1) {
            result = "不久之前";
        }else if(1<(s-c) && (s-c)<2){
            result = "1小时之前";
        }else if(2<(s-c) && (s-c)<3){
            result = "2小时之前";
        }else if(3<(s-c) && (s-c)<4){
            result = "3小时之前";
        }else if((s-c)>4){
            result = "很久之前";
        }
            view.setText(result);
    }
}
